package com.wkk.shiro;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * 自定义Realm
 * 
 * @author admin
 *
 */
public class CustomRealm extends AuthorizingRealm {
	// 模拟数据库存储账户和密码
	Map<String, Object> usermap = new HashMap<String, Object>();
	{
		usermap.put("wkk", "1c437eac2e84238e43391e01077a2bde");
		super.setName("customRealm");

	}

	@Override // 授权(在已通过验证的前提下，获取对应角色和权限，并传入管理器等待调取和判断)
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String user_name = (String) principals.getPrimaryPrincipal();
		Set<String> roles = getRoleByUserName(user_name);

		Set<String> permission = getPermissionByUserName(user_name);
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.setStringPermissions(permission);
		simpleAuthorizationInfo.setRoles(roles);
		return simpleAuthorizationInfo;
	}

	@Override // 登陆认证(验证账户是否存在，密码是否正确)
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// 1.获取用户传来的用户名
		String username = (String) token.getPrincipal();
		// 2.通过这个用户名获取数据库中存的已有的加密过的密码
		String password = getPassWordByUserName(username);
		if (password == null) {
			// 如果不存在的账户

			return null;
		}
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password,
				"customRealm");
		simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("wkk"));// 解盐

		// 到此处，返回一个解盐后的，用户登陆的已有帐户的关联账户加密密码的token,待稍后解密后与用户实际输入的用户名密码比较

		return simpleAuthenticationInfo;

	}

	// 模拟从数据库获取password
	private String getPassWordByUserName(String user_name) {
		return (String) usermap.get(user_name);

	}

	// 模拟从数据库获取role
	private Set<String> getRoleByUserName(String user_name) {
		Set<String> sets = new HashSet<String>();// 模拟
		sets.add("admin");
		sets.add("vend");

		return sets;

	}

	// 模拟从数据库获取permission
	private Set<String> getPermissionByUserName(String user_name) {
		Set<String> sets = new HashSet<String>();// 模拟
		sets.add("user:delete");

		return sets;

	}

}
